#ifndef MSGPROTO_H
#define MSGPROTO_H

#include <stdint.h>
#include <QByteArray>

#define MP_START    0xEF01

#define MP_CMD_UPCHAR    0x08
#define MP_CMD_DOOR      0x09
#define MP_CMD_LTCTL     0x10
#define MP_CMD_SWV       0x11
#define MP_CMD_RLCTL     0x12

#pragma pack(1)
typedef struct
{
    uint16_t start;
    uint32_t addr;
    uint8_t type;
    uint16_t len;
    uint8_t cmd;
}proto_hdr_t;

typedef struct
{
    proto_hdr_t hdr;
    uint8_t data[256];
    uint16_t sum;
}upchar_req_t;

typedef struct
{
    proto_hdr_t hdr;
    uint8_t op;
    uint16_t sum;
}doorctrl_req_t;

typedef struct
{
    proto_hdr_t hdr;
    uint8_t ch;
    uint16_t sum;
}swv_req_t;

typedef struct
{
    proto_hdr_t hdr;
    uint8_t ch;
    uint8_t op;
    uint16_t sum;
}relays_req_t;
#pragma pack()

class msgproto
{
public:
    msgproto();

    bool in(char *buf, int size, int &cmd);

public:
    QByteArray makeDoorCtrl(uint8_t op);
    QByteArray makeLightCtrl(uint8_t op);
    QByteArray makeSwitchVal(uint8_t ch);
    QByteArray makeRelaySpare(uint8_t ch, uint8_t op);

private:
    uint16_t chksum(uint8_t *data, int size);
    uint16_t swap(uint16_t v);
    void cmd_hdrinit(QByteArray &buf, uint8_t cmd, uint16_t len);
};

#endif // MSGPROTO_H
